import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/Home.vue'
import about from '../views/About.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import(/* webpackChunkName: "goods" */ '../views/Goods.vue')
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/error',
    name: 'error',
    component: () => import(/* webpackChunkName: "error" */ '../components/Error.vue')
  },
  {
    path: '/personal',
    name: 'personal',
    component: () => import ('../views/Personal.vue'),
    meta: {
      requiresAuth: true // 需要验证登录状态
    }
  },
  {
    path: '/detail',
    name: 'detail',
    component: () => import('../views/ProductDetail.vue')
  },
  {
    path: '/shopCart',
    name: '/cart',
    component: () => import ('../views/Cart.vue')
  },
  {
    path: '/loginFirst',
    name: '/loginFirst',
    component: () => import ('../views/LoginFirst.vue')
  },
  {
    path: '/order',
    name: 'order',
    query: {from: 4},
    component: () => import('../views/Personal.vue'),
    meta: {
      requiresAuth: true // 需要验证登录状态
    }
  },
  {
    path: '/list',
    name: 'list',
    component: () => import('../views/List.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('user') !== "" && localStorage.getItem('user') !== null && localStorage.getItem('user') !== undefined;

  // 在这里判断用户是否登录
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth); // 获取当前路由的 meta.requiresAuth 属性

  if (requiresAuth && !isAuthenticated) {
    next('/loginFirst'); // 无权限，重定向到首页
  } else {
    next(); // 否则放行
  }
});

export default router